﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using KPIS.GERP.Models;
using KPIS.GERP.Models.HRM;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.Models.SYS.ViewModel;
using KPIS.GERP.WEB.GAMS.Class;
using KPIS.GERP.WEB.GAMS.Class;
//
using WebMatrix.WebData;

namespace KPIS.GERP.WEB.GAMS.Controllers
{
    [Authorize]
    //
    public class HomeController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult Login()
        {
            //if (WebSecurity.IsAuthenticated && GimsConfigReader.WhenGoToLoginPage == GimsConfigReader.WhenGoToLoginPageEnum.LogOff)
            //    WebSecurity.Logout();

            //// If logged in, redirect to home page
            //if (WebSecurity.IsAuthenticated )
            //{
            //    using (var gs = new GerpAuthenService.GerpAuthenServiceClient())
            //    {
            //        Employee employee = new UserService.UserServiceClient().GetEmployeeByUser(GimsMembership.CurrentUserId);

            //        if (employee == null) return ShowSomeMessage("Can't load employee");

            //        gs.Login(GimsMembership.CurrentUserId, GimsUtilities.ClientIp, GimsUtilities.ThisSystemId, 
            //            GimsMembership.CurrentUserName, employee.FullName, employee.PosId);
            //    }

            //    return RedirectToAction(GimsConfigReader.WhenGoToLoginPage == GimsConfigReader.WhenGoToLoginPageEnum.StayAtLogin ? "Login" :  "Index" );
            //}
            return View();
        }

        [AllowAnonymous]
        public ActionResult SingleSigon(string tokenKey, string redirectPage)
        {
            //if (WebSecurity.IsAuthenticated)
            //    WebSecurity.Logout();

            using (var gs = new GerpAuthenService.GerpAuthenServiceClient())
            {
                //UserTempInfo  userTempInfo;
                Dictionary<string, string> dataLogin = gs.GetAndDestroyOTP(tokenKey);
                if (dataLogin == null) return Content("No data of your share key data, or data has expire or been used.");
                if (string.IsNullOrWhiteSpace(dataLogin["UserCode"]) || string.IsNullOrWhiteSpace(dataLogin["Password"])) return Content("No or incomplete user information in share data");

                if (!WebSecurity.Login(dataLogin["UserCode"], dataLogin["Password"])) return Content("Data share we got can't be login because it unauthenticated.");

                User user = new UserService.UserServiceClient().GetUser(GimsMembership.CurrentUserId);
                Employee employee = new UserService.UserServiceClient().GetEmployeeByUser(GimsMembership.CurrentUserId);

                if (user == null || employee == null) return ShowSomeMessage("Can't load user or employee");

                gs.Login(GimsMembership.CurrentUserId, GimsUtilities.ClientIp, GimsUtilities.ThisSystemId, user.Code, employee.FullName, employee.PosId);
            }

            if (!string.IsNullOrWhiteSpace(redirectPage))
                return Redirect(redirectPage);

            return RedirectToAction("Index");
        }

        [AllowAnonymous]
        public ActionResult SingleSigonRawData(string username, string password, string redirectPage)
        {
            //if (WebSecurity.IsAuthenticated)
            //    WebSecurity.Logout();

            using (var gs = new GerpAuthenService.GerpAuthenServiceClient())
            {
                if (!WebSecurity.Login(username, password)) return Content("Invalid authenticate.");
                var currentUserId = WebSecurity.GetUserId(username);
                User user = new UserService.UserServiceClient().GetUser(currentUserId);
                Employee employee = new UserService.UserServiceClient().GetEmployeeByUser(currentUserId);

                if (user == null || employee == null) return ShowSomeMessage("Can't load user or employee");

                gs.Login(currentUserId, GimsUtilities.ClientIp, GimsUtilities.ThisSystemId, user.Code, employee.FullName, employee.PosId);
            }

            if (!string.IsNullOrWhiteSpace(redirectPage))
                return Redirect(redirectPage);

            return RedirectToAction("Index");
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(LoginModel model, string RememberMeChb)
        {
            model.RememberMe = (RememberMeChb == "on");
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                Employee employee;
                using (var us = new UserService.UserServiceClient())
                {
                    var user = us.GetUserByUserCode(model.UserName);

                    if (user == null)
                    {
                        // Remark: หากมาถึงตรงนี้ แบบว่าตาราง SysUser ไม่มีข้อมูลของผู้ใช้นี้ แต่มีอยู่ในตาราง UserProfile ของระบบ MemberShip
                        // มันไม่ควรเกิดขึ้น เพราะหากสร้างหรือลบ User ก็ควรทำทั้ง WebSecurity และ SysUser ไปด้วยกัน
                        var notFoundInSysUserExc = new Exception("Not found this user in SysUser");

                        // Option#1 throw error
                        // throw notFoundInSysUserExc;

                        // Option@2 show as message error in model
                        ModelState.AddModelError("", notFoundInSysUserExc.Message);

                        WebSecurity.Logout();

                        return View(model);
                    }

                    employee = new UserService.UserServiceClient().GetEmployeeByUser(user.UserId);
                }
                if (employee == null)
                {
                    var notFoundInEmployeeExc = new Exception("Not found current employee in database");

                    ModelState.AddModelError("", notFoundInEmployeeExc.Message);

                    WebSecurity.Logout();

                    return View(model);
                }

                using (var gs = new GerpAuthenService.GerpAuthenServiceClient())
                {
                    gs.Login(GimsMembership.CurrentUserId, GimsUtilities.ClientIp,
                        GimsUtilities.ThisSystemId, model.UserName, employee.FullName, employee.PosId);
                }
                return RedirectToAction("Index", "Home");
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

        [AllowAnonymous]
        public ActionResult _Error404()
        {
            return PartialView();
        }

        [AllowAnonymous]
        public ActionResult _Error500()
        {
            return PartialView();
        }

        [ActionName("LogOff")]
        [HttpPost]
        public ActionResult LogOffByPost()
        {
            return LogOffPrivate();
        }

        [ActionName("LogOff")]
        public ActionResult LogOffByGet()
        {
            return LogOffPrivate();
        }

        [NonAction]
        private ActionResult LogOffPrivate()
        {
            var userId = GimsMembership.CurrentUserId;
            WebSecurity.Logout();
            //User user = new UserService.UserServiceClient().GetUser(userId);
            Employee employee = new UserService.UserServiceClient().GetEmployeeByUser(userId);
            //if (user == null) return ShowSomeMessage("Not found current user in database");
            if (employee == null) return ShowSomeMessage("Not found current employee in database");
            using (var gs = new GerpAuthenService.GerpAuthenServiceClient())
            {
                gs.AddOrUpdateMonitor(userId, GimsUtilities.ClientIp, GimsUtilities.ThisSystemId, GimsMembership.CurrentUserName, employee.FullName, employee.PosId, "Log out", null);
                GimsMembership.AuditLogout();
            }
            return RedirectToAction("Login", "Home");
        }

        [HttpPost]
        public ActionResult Search(string keyword)
        {
            return Content("ผลการค้นหาด้วย Keyword " + keyword + " มีจำนวน 30 ผลลัพธ์ดังนี้....");
        }

        [AllowAnonymous]
        public ActionResult ShowSomeMessage(string message, string urlBack = null)
        {
            ViewBag.Message = message;
            ViewBag.Url = urlBack;
            return View("ShowSomeMessage");
        }
    }
}
